package vn.edu.saigontech.ncms.util;

import java.io.*;
import java.util.*;

public abstract class PropertiesFile {
	protected Properties properties = new Properties();
	
	public boolean contains(String key) {
		return this.properties.containsKey(key);
	}
	
	public boolean containsValue(String value) {
		return this.properties.containsValue(value);
	}
	
	public void remove(String key) {
		this.properties.remove(key);
	}
	
	public void delete(String key) {
		this.remove(key);
		this.store();
	}
	
	public String getValue(String key) {
		return this.properties.getProperty(key);
	}
	
	public void setValue(String key, String value) {
		this.properties.setProperty(key, value);
	}
	
	public void saveValue(String key, String value) {	
		this.properties.setProperty(key, value);
		this.store();
	}
	
	public File getPath() {
		return new File(this.getLocation());
	}
	
	public File getParent() {
		return this.getPath().getParentFile();
	}
	
	public void load() {
		this.properties.clear();
		BufferedInputStream bis = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(this.getLocation()));
			this.properties.load(bis);
		} 
		catch (Exception ex) {
			ex.printStackTrace();
		}
		finally {
			if(bis != null) {
				try {
					bis.close();
				} 
				catch (IOException ex1) {}
			}
		}
	}
	
	public void store() {
		BufferedOutputStream bos = null;
		try {
			bos = new BufferedOutputStream(new FileOutputStream(this.getLocation()));
			this.properties.store(bos, this.getTitle());
		} 
		catch (Exception ex) {
			ex.printStackTrace();
		}
		finally {
			if(bos != null) {
				try {
					bos.close();
				} 
				catch (IOException ex1) {}
			}
		}
	}
	
	public Properties getProperties() {
		return this.properties;
	}
	
	public abstract String getTitle();
	public abstract String getLocation();
}